<template>
  <div class="purchase-demand-page">
    <!-- 页面标题 -->
    <h3 class="page-title">求购信息</h3>
    
    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-row :gutter="20" class="search-container">
        <!-- 分类树状下拉 -->
        <el-col :span="4">
          <el-tree-select 
            v-model="searchParams.typeId" 
            placeholder="分类" 
            clearable
            :data="typeTree"
            :props="{ label: 'typeName', value: 'typeId', children: 'children' }"
            class="search-select"
          ></el-tree-select>
        </el-col>
        <el-col :span="4">
          <el-input 
            v-model="searchParams.contactName" 
            placeholder="联系人" 
            clearable
            class="search-input"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card" :loading="loading">
      <el-table 
        :data="purchaseList" 
        border 
        stripe
        style="width: 100%;"
        :row-class-name="tableRowClassName"
        @row-hover="handleRowHover"
        :fit="true"
      >
        <el-table-column prop="purchaseId" label="ID" width="80"></el-table-column>
        <el-table-column label="求购设备类型-品牌" width="160">
          <template #default="scope">
            <span class="type-brand">{{ scope.row.type?.typeName || '未知' }}-{{ scope.row.brand || '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="求购信息" width="220">
          <template #default="scope">
            <div class="demand-info">
              <div class="main-info">{{ scope.row.contactName || '未知' }}求购{{ formatPriceRange(scope.row) }}{{ scope.row.type?.typeName || '未知设备' }}</div>
              <div class="sub-info">产生时间: {{ formatTime(scope.row.releaseTime) }}</div>
              <div class="sub-info">更新时间: {{ formatTime(scope.row.updateTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="求购价格" width="140">
          <template #default="scope">
            <span class="price">{{ formatPriceRange(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="联系人" width="120">
          <template #default="scope">
            <div class="contact-info">
              <span>{{ scope.row.contactName || '未知' }}</span>
              <el-button 
                type="success" 
                size="mini" 
                round 
                class="contact-btn"
                @click="showContact(scope.row)"
              >
                <el-icon><Phone /></el-icon>
                联系
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="region" label="求购状态" width="140">
          <template #default="scope">
            <div class="status-container">
              <el-tag :type="getStatusTagType(scope.row.purchaseStatus)">
                {{ getStatusText(scope.row.purchaseStatus) }}
              </el-tag>
              <el-button 
                v-if="scope.row.purchaseStatus === 0"
                type="primary" 
                size="mini" 
                @click="handleAssign(scope.row)"
                class="assign-btn"
              >
                分配
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户名(UID)" width="180">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :size="24" :src="scope.row.user?.avatar || ''" class="user-avatar"></el-avatar>
              <span>{{ scope.row.user?.userName || '未知用户' }} ({{ scope.row.userId }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button 
                type="info" 
                size="small" 
                @click="viewDetail(row)"
              >
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </div>
    
    <!-- 联系信息弹窗 -->
    <el-dialog 
      v-model="contactDialogVisible" 
      title="联系方式" 
      width="30%"
      :close-on-click-modal="false"
    >
      <div v-if="currentContactInfo" class="contact-dialog-content">
        <div class="contact-avatar">
          <el-avatar :size="60" icon="User"></el-avatar>
        </div>
        <div class="contact-details">
          <p><span class="label">联系人:</span> {{ currentContactInfo.contactName || '未知' }}</p >
          <p><span class="label">电话:</span> {{ currentContactInfo.contactPhone || '未知' }}</p >
          <p><span class="label">需求:</span> {{ currentContactInfo.contactName || '未知' }}求购{{ formatPriceRange(currentContactInfo) }}{{ currentContactInfo.type?.typeName || '未知设备' }}</p >
        </div>
      </div>
      <template #footer>
        <el-button @click="contactDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

        <!-- 分配业务员模态框 -->
    <el-dialog
      v-model="allocateDialogVisible"
      title="分配业务员"
      width="500px"
      :before-close="closeAllocateDialog"
      destroy-on-close
    >
      <!-- 搜索区域 -->
      <div class="allocate-search">
        <el-input
          v-model="businessmanQuery.keyword"
          placeholder="输入用户名或姓名搜索"
          class="search-input"
          @keyup.enter="getBusinessmanList"
        >
          <template #append>
            <el-button type="primary" @click="getBusinessmanList">查找</el-button>
          </template>
        </el-input>
      </div>

      <!-- 业务员列表 -->
      <el-table
        :data="businessmanList"
        border
        v-loading="businessmanLoading"
        element-loading-text="加载中..."
        class="businessman-table"
      >
        <el-table-column label="姓名" prop="name" width="350"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="confirmAllocate(scope.row)"
            >
              选择分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="businessman-pagination">
        <el-pagination
          v-model:current-page="businessmanPagination.currentPage"
          v-model:page-size="businessmanPagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="businessmanPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleBusinessmanSizeChange"
          @current-change="handleBusinessmanCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="closeAllocateDialog">取消</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog 
      title="评估详情" 
      v-model="detailDialogVisible" 
      width="600px"
      class="detail-dialog"
    >
      <el-scrollbar max-height="500px">
        <el-form label-width="120px" class="detail-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="ID：">
                {{ currentRow.purchaseId }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类型-品牌：">
                {{ currentRow.type.typeName }} - {{currentRow.brand}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="方量：">
                {{ currentRow.workVolume }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出厂年份：">
                {{ currentRow.expectedYear }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="用户名(UID)：">
            {{ currentRow.user.userName }} ({{ currentRow.userId }})
          </el-form-item>
          <el-form-item label="审核状态：">
            <el-tag :type="getStatusTagType(currentRow.purchaseStatus)">
              {{ getStatusText(currentRow.purchaseStatus) }}
            </el-tag>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import httpInstance from '../../utils/http';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Phone, Edit, Delete, User } from '@element-plus/icons-vue';
import { ElTreeSelect } from 'element-plus'; // 引入树形选择器

// 状态变量
const purchaseList = ref([]);
const typeTree = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const contactDialogVisible = ref(false);
const currentContactInfo = ref(null);
const loading = ref(false);
const hoverRow = ref(null);

// 搜索参数
const searchParams = ref({
  typeId: '',
  contactName: ''
});

// 分配业务员相关数据
const allocateDialogVisible = ref(false);
const currentAllocateEquipment = ref(null);
const businessmanList = ref([]);
const businessmanLoading = ref(false);
const businessmanQuery = reactive({
  keyword: ''
});
const businessmanPagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

// 当前行数据
const currentRow = ref({});
// 详情对话框
const detailDialogVisible = ref(false);
// 查看详情
const viewDetail = (row) => {
  console.log('查看详情', row);
  currentRow.value = row;
  detailDialogVisible.value = true;
};

// 获取设备类型树状列表
const getTypeTree = async () => {
  try {
    const response = await httpInstance.get('/eduservice/equipmentType/getTypeTree');
    if (response.data.success) {
      typeTree.value = response.data.data.typeTree;
    }
  } catch (error) {
    console.error('获取设备类型失败:', error);
    ElMessage.error('获取设备类型失败，请重试');
  }
};

// 获取求购信息列表
const getPurchaseList = async () => {
  loading.value = true;
  try {
    const response = await httpInstance.post(
      `/eduservice/purchaseDemand/getPurchaseDemandPageList/${pageNum.value}/${pageSize.value}`,
      searchParams.value
    );
    const data = response.data;
    purchaseList.value = data.list;
    total.value = data.total;
    console.log('求购信息列表:', purchaseList.value);
  } catch (error) {
    console.error('获取求购信息失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 获取业务员列表数据分页
const getBusinessmanList = async () => {
  businessmanLoading.value = true;
  try {
    // 构造查询参数
    const businessmanVo = {
      username: businessmanQuery.keyword,
      name: businessmanQuery.keyword // 假设后端支持按用户名或姓名搜索
    };

    const response = await httpInstance.post(
      `/eduservice/businessman/getBusinessmanPage/${businessmanPagination.currentPage}/${businessmanPagination.pageSize}`,
      businessmanVo
    );

    // 假设接口返回格式为 { list: [], total: 0 }
    businessmanList.value = response.data.list || [];
    businessmanPagination.total = response.data.total || 0;

  } catch (error) {
    ElMessage.error('获取业务员列表失败');
    console.error('业务员列表请求错误:', error);
  } finally {
    businessmanLoading.value = false;
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(',', '');
};

// 格式化价格区间（支持区间或单价格）
const formatPriceRange = (row) => {
  return row.priceRange || (row.expectedPrice ? (row.expectedPrice / 10000).toFixed(2) + '万' : '-');
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待处理';
    case 1: return '已分配';
    case 2: return '已成交';
    case 3: return '已取消';
    default: return '未知状态';
  }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'info';    // 待处理 - 灰色
    case 1: return 'primary'; // 已分配 - 蓝色
    case 2: return 'success'; // 已成交 - 绿色
    case 3: return 'danger';  // 已取消 - 红色
    default: return 'info';
  }
};

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1; // 重置到第一页
  getPurchaseList();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getPurchaseList();
};

// 当前页变化
const handleCurrentChange = (val) => {
  pageNum.value = val;
  getPurchaseList();
};

// 业务员分页大小变化
const handleBusinessmanSizeChange = (size) => {
  businessmanPagination.pageSize = size;
  getBusinessmanList();
};

// 业务员当前页变化
const handleBusinessmanCurrentChange = (page) => {
  businessmanPagination.currentPage = page;
  getBusinessmanList();
};

// 显示联系方式
const showContact = (row) => {
  currentContactInfo.value = row;
  contactDialogVisible.value = true;
};

// 分配按钮
const handleAssign = (row) => {
  currentAllocateEquipment.value = row;
  businessmanPagination.currentPage = 1;
  businessmanQuery.keyword = '';
  getBusinessmanList();
  allocateDialogVisible.value = true;
};

// 确认分配
const confirmAllocate = async (businessman) => {
  try {
    ElMessageBox.confirm(`确定将设备【${currentAllocateEquipment.value.brand}】分配给业务员【${businessman.name}】吗？`, '确认分配', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 调用分配接口
      httpInstance.post('/eduservice/purchaseDemand/updatePurchaseDemandByBusinessmanId', {
        purchaseId: currentAllocateEquipment.value.purchaseId,
        businessmanId: businessman.businessmanId
      }).then((response) => {
        if (response) {
          ElMessage.success('分配成功');
          getPurchaseList();
        } else {
          ElMessage.error('分配失败: ' + response.data.message);
        }
      }).catch((error) => {
        ElMessage.error('分配请求失败');
        console.error('分配请求错误:', error);
      });  
    }).catch(() => {
      ElMessage.error('取消分配');
    });
    
    // 关闭模态框
    allocateDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('分配失败，请重试');
    console.error('分配错误:', error);
  }
};

// 编辑处理
const handleEdit = (row) => {
  console.log('编辑:', row);
  // 实际应用中这里会跳转到编辑页面或打开编辑弹窗
};

// 行 hover 事件
const handleRowHover = (row, event) => {
  hoverRow.value = event.type === 'mouseenter' ? row : null;
};

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};

// 页面加载时获取数据
onMounted(() => {
  getTypeTree();
  getPurchaseList();
});
</script>

<style scoped>
/* 详情对话框样式 */
.detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.detail-form .el-form-item {
  margin-bottom: 15px;
}
/* 保持原有样式不变，新增树形选择器宽度适配 */
.search-select {
  width: 100%;
}

/* 响应式调整（小屏幕下优化列显示） */
@media (max-width: 1200px) {
  .el-table-column {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .el-table__cell {
    padding: 8px 4px !important;
  }
}

.contact-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/* 联系人文字样式 */
.contact-info span {
  font-weight: 500;
  color: #333;
}
/* 联系按钮 - 调整尺寸与间距 */
.contact-btn {
  padding: 4px 10px !important; /* 缩小按钮尺寸 */
  margin-left: 5px;
}

/* 用户名(UID)列 - 头像与文字对齐 */
.user-info {
  display: flex;
  align-items: center;
}
.user-avatar {
  margin-right: 8px;
}

/* 操作列 - 按钮间距与 hover 反馈 */
.operation-buttons {
  display: flex;
  gap: 8px; /* 按钮之间的间距 */
}
.edit-btn, .delete-btn {
  transition: all 0.2s ease;
}
.edit-btn:hover {
  background-color: #409EFF;
  color: #fff;
}
.delete-btn:hover {
  background-color: #F56C6C;
  color: #fff;
}
/* 表格行 hover 效果 */
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 联系按钮 hover 效果 */
.contact-btn:hover {
  background-color: #67C23A;
  color: #fff;
}

/* 状态容器 */
.status-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

/* 分配按钮 */
.assign-btn {
  margin-top: 5px;
}
</style>